package com.engine.modules.ytht.util;

import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.spec.InvalidParameterSpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import lombok.extern.slf4j.Slf4j;

/**
 * aes 加密解密
 * 
 * @author zgn
 *
 */
@Slf4j
public class SuperAESUtil {

	// 编码
	private static final String ENCODING = "UTF-8";
	// 算法
	private static final String ALGORITHM = "AES";
	// 默认的加密算法
	private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

	private SuperAESUtil() {
		throw new IllegalStateException("SuperAESUtil class");
	}

//	/**
//	 * 对象 加密
//	 * 
//	 * @param <T>
//	 * @param sourceT
//	 * @param key
//	 * @param ivStr
//	 * @return
//	 * @throws Exception
//	 */
//	public static <T> String encryptEntityKeyIv(T sourceT, String key, String ivStr) throws Exception {
//		String sourceData = JSON.toJSONString(sourceT);
//		return encryptKeyIv(sourceData, key, ivStr);
//	}

	/**
	 * 加密
	 * 
	 * @param sourceData
	 * @param key
	 * @param ivStr
	 * @return
	 * @throws Exception
	 */
	public static String encryptKeyIv(String sourceData, String key, String ivStr) throws Exception {
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("ASCII"), ALGORITHM);
		IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
		byte[] encrypted = cipher.doFinal(sourceData.getBytes(ENCODING));
		return SuperBase64Util.encode(encrypted);// 此处使用BASE64做转码。
	}

	/**
	 * 解密
	 * 
	 * @param encryptData
	 * @param key
	 * @param ivStr
	 * @return
	 * @throws Exception
	 */
	public static String decryptKeyIv(String encryptData, String key, String ivStr) throws Exception {
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("ASCII"), ALGORITHM);
		IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
		byte[] buffer = SuperBase64Util.decode(encryptData);
		byte[] encrypted = cipher.doFinal(buffer);
		return new String(encrypted, ENCODING);// 此处使用BASE64做转码。
	}

	/**
	 * 加密
	 * 
	 * @param content待加密内容
	 * @param key          加密的密钥
	 * @return
	 */
	public static String encrypt(String content, String key) {
		try {
			// 构造密钥生成器，指定为AES算法，不区分大小写
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(key.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			byte[] byteContent = content.getBytes("utf-8");
			// ENCRYPT_MODE指加密操作
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			byte[] byteRresult = cipher.doFinal(byteContent);
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < byteRresult.length; i++) {
				String hex = Integer.toHexString(byteRresult[i] & 0xFF);
				if (hex.length() == 1) {
					hex = '0' + hex;
				}
				sb.append(hex.toUpperCase());
			}
			return sb.toString();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param content 待解密内容
	 * @param key     解密的密钥
	 * @return
	 */
	public static String decrypt(String content, String key) {
		if (content.length() < 1) {
			return null;
		}
		byte[] byteRresult = new byte[content.length() / 2];
		for (int i = 0; i < content.length() / 2; i++) {
			int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
			byteRresult[i] = (byte) (high * 16 + low);
		}
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(key.getBytes());
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// Decrypt_mode指解密操作
			byte[] result = cipher.doFinal(byteRresult);
			return new String(result, "utf-8");// 不加utf-8，中文时会乱码
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * AES解密
	 *
	 * @param data           //密文，被加密的数据
	 * @param key            //秘钥
	 * @param iv             //偏移量
	 * @param encodingFormat //解密后的结果需要进行的编码
	 * @return
	 * @throws Exception
	 */
	public static String aesDecrypt(String data, String key, String iv, String encodingFormat) throws Exception {

		// 被加密的数据
		byte[] dataByte = Base64.decodeBase64(data);
		// 加密秘钥
		byte[] keyByte = Base64.decodeBase64(key);
		// 偏移量
		byte[] ivByte = Base64.decodeBase64(iv);
		try {
			Security.addProvider(new BouncyCastleProvider());
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
			SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
			AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
			parameters.init(new IvParameterSpec(ivByte));
			cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
			byte[] resultByte = cipher.doFinal(dataByte);
			if (null != resultByte && resultByte.length > 0) {
				String result = new String(resultByte, encodingFormat);
				return result;
			}
			return null;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidParameterSpecException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
}
